#include <string>
#include <string.h>
#include <iostream>

#include "qdata_confusion.h"

QDataConfusion::QDataConfusion()
: data_(NULL)
{
}

QDataConfusion::~QDataConfusion()
{
    Clear();
}

char * QDataConfusion::Encrypt(const char * data, size_t count,
            const std::string &keys, size_t keyPos)
{
    char * ret = NULL;
    if(NULL==data || count<=0) {
        std::cout << "data count err=" << count << std::endl;
    } else {
        if(CreateDataSpace(count)) {
            CalculateData(data, count, keys, keyPos);
            ret = data_;
        }
    }
    return ret;
}

char * QDataConfusion::Decrypt(const char * data, size_t count,
            const std::string &keys, size_t keyPos)
{
    char * ret = NULL;
    if(NULL==data || count<=0) {
        std::cout << "data count err=" << count << std::endl;
    } else {
        if(CreateDataSpace(count)) {
            CalculateData(data, count, keys, keyPos);
            ret = data_;
        }
    }
    return ret;
}

bool QDataConfusion::CreateDataSpace(size_t count)
{
    Clear();
    data_ = new char[count];
    if(NULL == data_) {
        std::cout << "create new space failed." << std::endl;
        return false;
    }
    return true;
}

void QDataConfusion::Clear()
{
    if(data_) {
        delete [] data_;
        data_ = NULL;
    }
}

void QDataConfusion::CalculateData(const char * data, size_t count,
            const std::string &keys, size_t keyPos)
{
    const char * ptr = data;
    const char * keyPtr = keys.c_str();
    size_t kLen = keys.length();
    for(size_t i=0; i<count; ++i, ptr++) {
        //int curPos = (i+keyPos)%kLen;
        int curPos = 5;
        //data_[i] =  ~*ptr^keys[curPos];
        data_[i] =  ~*ptr^(*(keyPtr+curPos)); //提升效率
    }
}
